<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/11 0011
 * Time: 16:20
 */

namespace app\api\controller\v1;


use app\currency\service\ExtendService;
use library\Controller;
use library\tools\Data;

class Sms extends Controller
{
    /**
     * 发送短信
     * @param $id
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function read($id)
    {
        $data = $this->_input([
            'phone' => $id,
        ],[
            'phone' => 'require|mobile'
        ],[
            'phone.require' => '请填写手机号！',
            'phone.mobile'  => '请填写正确的手机号！'
        ]);
        $cache = cache($cachekey = "send_register_sms_{$data['phone']}");
        $sys_code_reset_in = intval(sysconf('sys_code_reset_in')) ?: 60;//验证码发送间隔时间
        if (is_array($cache) && isset($cache['time']) && $cache['time'] > time() - $sys_code_reset_in) {
            $dtime = ($cache['time'] + $sys_code_reset_in < time()) ? 0 : ($sys_code_reset_in - time() + $cache['time']);
            $this->success('短信验证码已经发送！', ['time' => $dtime]);
        }
        $sys_code_length = intval(sysconf('sys_code_length')) ?: 4;//验证码长度
        list($code, $content) = [Data::randomCode($sys_code_length), sysconf('sms_reg_template')];
        if (empty($content) || strpos($content, '{code}') === false) {
            $this->error('获取短信模板失败，联系管理员配置！');
        }
        $sys_code_expire_in = intval(sysconf('sys_code_expire_in')) ?: 600;//验证码有效期
        cache($cachekey, ['phone' => $data['phone'], 'captcha' => $code, 'time' => time()], $sys_code_expire_in);
        $cache = cache($cachekey);
        $ExtendService = new ExtendService();
        if ($ExtendService->sendSms($data['phone'], str_replace('{code}', $code, $content))) {
            $dtime = ($cache['time'] + $sys_code_reset_in < time()) ? 0 : ($sys_code_reset_in - time() + $cache['time']);
            $this->success('短信验证码发送成功！', ['time' => $dtime]);
        } else {
            $this->error('短信发送失败，请稍候再试！');
        }
    }
}